/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.virtual.model.jcr;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;

/**
 *
 * @author Walter Luetgenau
 */
public class PropertyValueFormatter {
    /**
     * Format a single value to a string
     * @param value
     * @return
     * @throws javax.jcr.RepositoryException
     */
    public static String format(Value value) throws RepositoryException {
        switch (value.getType()) {
            case PropertyType.DATE:
                return DateFormat.getDateTimeInstance().format(value.getDate().getTime());
                
            default:
                return value.getString();                
        }
    }
    
    /**
     * Format an array of values
     * 
     * @param values
     * @return
     * @throws javax.jcr.RepositoryException
     */
    public static String[] format(Value[] values) throws RepositoryException {
        String[] result = new String[values.length];
        
        for (int i=0; i<result.length; i++)
            result[i] = format(values[i]);
        
        return result;
    }
    
    public static Value parse(int valueType, ValueFactory factory, String value) throws ParseException {
        Value result;
        
        switch (valueType) {
            case PropertyType.DATE:
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateFormat.getDateTimeInstance().parse(value));
                result = factory.createValue(calendar);
                break;
                
            default:
                result = factory.createValue(value);
        }
        
        return result;
    }
    
    public static Value[] parse(int valueType, ValueFactory factory, String[] values) throws ParseException {
        Value[] result = new Value[values.length];
        
        for (int i=0; i<result.length; i++)
            result[i] = parse(valueType, factory, values[i]);
        
        return result;
    }
}
